import React from 'react';
import { Route, Switch, Redirect} from 'react-router-dom';
import { RouteLayout } from 'weaver-mobile-page';
import { List,Tools,TextareaItem,Button,InputItem,Result,Icon,Bubble } from 'weaver-mobile';
import { BrowserHrm, Browser} from 'weaver-mobile-page';
import { inject,observer} from 'mobx-react';
import { toJS } from 'mobx';
const getLabel = Tools.getLabel;
const { FormItem } = List;
@inject('smsStore')
@observer
export default class Sms extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    const {getBaseData} = this.props.smsStore;
    let params = {};
     /* 查看时支持route的两种形式： 
      1, /sendSms?hrmid=**&crmid=**&customernumber=** 
      2, route.push({pathname: /sendSms, query{hrmid: **,crmid: **}})
    */
    const URL = this.props.location.search ? this.props.location.search.split('?')[1] : ''
    const url = URL.length > 0 ? URL.split('&') : [];
    const Arr = this.getQuery(url);
    let hrmid = this.props.location.search ? Arr['hrmid'] : this.props.location&&this.props.location.query&&this.props.location.query.hrmid;
    let crmid = this.props.location.search ? Arr['crmid'] : this.props.location&&this.props.location.query&&this.props.location.query.crmid;
    let customernumber = this.props.location.search ? Arr['customernumber'] : this.props.location&&this.props.location.query&&this.props.location.query.customernumber;
    let src = this.props.location.search ? Arr['src'] : this.props.location&&this.props.location.query&&this.props.location.query.src;
    let requestid = this.props.location.search ? Arr['requestid'] : this.props.location&&this.props.location.query&&this.props.location.query.requestid;

    params.hrmid = hrmid; // 接收人id '8088'
    params.customernumber = customernumber; // 自定义号码
    params.crmid = crmid; // 客户联系人id
    src && (params.src = src)
    requestid && (params.requestid = requestid)
    getBaseData(params);
    this.setInputSms() 
  }

  getQuery = (search)=>{
    let params ={}
    search.map((v,index)=>{
      const tempV = v.split('=');
      params[tempV[0]] = tempV[1];
      return '';
    });
    return params
  }

  setInputSms = () => {
    let inputSms = this.refs.inputsms;
    const keyDown = (e) => {
      const {listArr,setParams} = this.props.smsStore;
      if((e.keyCode === 8 ||e.key === 'Backspace') && inputSms.innerText.length < 1) { // 删除前一个号码
        if(listArr.length>0) {
          let arr = [];
          for(let i=0;i<listArr.length-1; i++) {
            arr.push(listArr[i])
          }
          setParams({listArr: arr});
        }
      }
      if((e.keyCode === 13 || e.key === 'Enter') && inputSms.innerText !== '') { // 添加一个号码
        let arr = listArr;
        arr.push(inputSms.innerText.replace(/[^\d]/g,'')); // 去除数字以外字符
        inputSms.innerText = '';
        setParams({listArr: arr});
        e.preventDefault(); // 阻止换行
      }
    }
    inputSms && inputSms.addEventListener('keydown',keyDown,false);
  }

  receiveHrm = (arg) => {
    const {setParams} = this.props.smsStore;
    setParams({hrmids: arg[0],browserHrmValue: arg[2]})
  }

  clientHrm = (arg) => {
    const {setParams,} = this.props.smsStore;
    setParams({crmids: arg[0], browserClientValue: arg[2]})
  }
  

  setSmsContent = (sms) => {
    const {setParams} = this.props.smsStore;
    setParams({smsContent: sms});
  }

  sendSms = () => {
    const {listArr} = this.props.smsStore;

    const {browserHrmValue,browserClientValue,smsContent,sendSms,hrmids,crmids,} = this.props.smsStore;
    let cusinfo = [];
    listArr && listArr.map(res => { cusinfo.push(res);return '';})
    let params = {
      sender: '',
      msg: smsContent,
      crmIds: crmids,
      requestid: '',
      cusNumber: cusinfo,
      hrmIds: hrmids,
    }
    // if((browserHrmValue !== '' || toJS(browserClientValue) !== []) && smsContent !== ''){
      // }
    if((cusinfo&&cusinfo.length > 0 || browserHrmValue && toJS(browserHrmValue).length > 0 || browserClientValue && toJS(browserClientValue).length > 0) && (smsContent && smsContent !== '')) {
      sendSms(params,() => this.props.history.push('sendSms/result'));
      
    }else{
      if(typeof(smsContent) === 'undefined' || smsContent === '') {
        Bubble.error(getLabel(384506,'短信内容不能为空！'), 1)
      }else{
        Bubble.error(getLabel(84463,'接收人不能为空!'), 1)
      }
    }
  }



  getHeight = () => {
    return window.innerHeight - (34+47)*window.getThemeVars()['hd'];
  }

  onBlur = () => {
    // 失去焦点
    const {listArr,setParams} = this.props.smsStore;

    let inputSms = this.refs.inputsms;
    if(inputSms.innerText !== '') {
      let arr = listArr;
      arr.push(inputSms.innerText.replace(/[^\d]/g,'')); // 去除数字以外字符
      inputSms.innerText = '';
      setParams({listArr: arr});
    }
  }

  onClickFocus = () => {
    // 点击自定义区域，输入框获得焦点
    this.refs.inputsms.focus();
  }

  getUserDef = () => {
    let fields = [];
    let Arr = [];
    const {listArr} = this.props.smsStore;
    const liMap = (arr) => {
      arr && arr.map((res, index) => {
        Arr.push(
          <li key={index} className='ul-li'><span className='label'>{res}</span></li>
        )
        return '';
      })
      return Arr;
    }
    fields.push(
      <div className='select-content' key='select-content' onClick={() => this.onClickFocus()} >
          <ul className='select-content-ul' key='select-content'>
            {/* <li></li> */}
            {liMap(listArr)}
            <li key='b' className='ul-li'><div className='label input' contentEditable={true} ref='inputsms' onBlur={() =>this.onBlur()}></div></li>
          </ul>
      </div>
    )
    return fields;
  }

  getFields = () => {
    const {browserHrm,browserHrmValue,browserClient,browserClientValue,smsContent,
            canSend,isGov,sendCrm,showCusSign,showReply} = this.props.smsStore;
    let fields = [];
    const u = navigator.userAgent;
    const Android =  u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    canSend && fields.push(
      <div className="sms-content" key='sms-content'>
        <div className='sms-content-header'>
            <div className='title'>{getLabel(16635,'发送短信')}</div>
        </div>

        <div className='list' >
          <List>
            <FormItem
              key={1}
              label={getLabel(32926,'短信接收员工')}
              wrap="nowrap"
              line
              content={(
                <BrowserHrm
                  store={browserHrm}
                  hasAdvanceSerach
                  isSingle={false}
                  type={1}
                  onChange={(...arg) => {
                    this.receiveHrm(arg);
                  }}
                  valueArray={browserHrmValue}
                />
              )}
            />
            {!isGov && <FormItem
              key={2}
              label={getLabel(32928, '短信接收客户联系人')}
              wrap="nowrap"
              line
              content={(
                <Browser
                  store={browserClient}
                  hasAdvanceSerach
                  isSingle={false}
                  type={7}
                  onChange={(...arg) => {
                    this.clientHrm(arg);
                  }}
                  valueArray={browserClientValue}
                />
              )}
            />}
            <div className='no-border'>
              <FormItem
                key={3}
                label={getLabel(18538, '自定义号码')}
                wrap="nowrap"
                line
                content={(
                  this.getUserDef()
                )}
              />
            </div>
            <FormItem
              key={11}
              wrap="nowrap"
              line
              content={(<InputItem editable={false} style={{fontSize: Android ? '12px' : '14px'}} defaultValue={getLabel(500645,"输入号码后请用换行进行确认")} />)}
            />
            <FormItem
              key={4}
              label={getLabel(18529, '短信内容')}
              wrap="nowrap"
              line
              required={(smsContent && smsContent !== '') ? false : true}
              content={(
                <TextareaItem
                  placeholder={getLabel(83869, '请输入')}
                  data-seed="logId"
                  autoHeight
                  value={smsContent}
                  onChange={v => this.setSmsContent(v)}
                  // rows={1}
                />
              )}
            />
          </List>
          {showReply && <div className='sms-content-remind'>
            <span className='reply'>{getLabel(500646, '回复方法：回复 ID+R+回复内容 （ID从收到的短信中可以获得）')}</span><br/>
            <span className='example'>{getLabel(500647, '例如：')}</span>
            <span className='label'>{getLabel(500648, '收到的信息为：')}</span><span className='content'>{getLabel(384503, '收到的消息内容(86)')} </span><br/>
            <span className='label'>{getLabel(384504, '回复应该为：')}</span><span className='content'>{getLabel(384505, '86R 发送的消息内容')}</span>
          </div>}
        </div>

        <div className='sms-content-send'>
          <Button type="primary" onClick={() => {this.sendSms()}} >
            {getLabel(2083, '发送')}
          </Button>
        </div>
      </div>
    );
    !canSend && fields.push(
      <div className='no-right'>
        <div className='icon-noright'>
          <Icon type='wuquanxian' size='lg'/>
        </div>
        <div className='message'>
          {getLabel(2012,'对不起，您暂时没有权限！')}
        </div>
      </div>
    );
    return fields;
  }

  getResult = () => {
    let fields = [];
    const {successflag,setParams} = this.props.smsStore;
    fields.push(
      <div className='sms-reslut' key='sms-reslut'>
        {successflag ? <Result
          img={<Icon type="check-circle" className="spe" style={{ fill: '#1F90E6' }} />}
          title={getLabel(384209,"短信发送成功")}
          // message="所提交内容已成功完成验证"
        />
        :
        <Result
          img={<Icon type="cross-circle-o" className="spe" style={{ fill: '#F13642' }} />}
          title={getLabel(24544,"短信发送失败")}
          // message="所提交内容已成功完成验证"
        />
        }
      </div>
    );
    return fields;
  }

  getLoading = () => {
    let fields = [];
    fields.push(
      <div className='loading'>
        <Icon type='loading'/>
      </div>
    );
    return fields;
  }

  render() {
    const {loading} = this.props.smsStore;
    return (
      <div className='sms-container'>
        {this.getFields()}
        <Switch>
          <Route
            key="result"
            path="**/result" 
            render={()=>(
              <RouteLayout>
              <div key="result" className="wm-route-layout sms-container">
                {this.getResult()}
              </div>
              </RouteLayout>
            )}
          />
          {/* <Redirect  exact to={{pathname: '/sendSms'}} /> */}
        </Switch>
      </div>
    )
  }
}

